<template>
    <div class="jianzhan-content">
        <Crumb name="Sparepart Request"></Crumb>
        <div class="content">
            <el-button
                    type="primary"
                    @click="openAdd"
            >Add New Request
            </el-button>
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Search By Customer"
                        prefix-icon="el-icon-search"
                ></el-input>
                <el-button
                        size="small"
                        type="primary"
                >Search
                </el-button>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="purchaseRequestList"
                        border
                        stripe
                        style="width: 100%">
                    <el-table-column
                            prop="requestNo"
                            label="Request Number"
                            width="180"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="requestDate"
                            label="Request Date"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="requestBy"
                            label="Request By"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="customer"
                            label="Customer"
                            width="250">
                    </el-table-column>
                    <el-table-column
                            prop="customerPo"
                            label="Po"
                            width="150">
                    </el-table-column>
                    <el-table-column
                            prop="purpose"
                            label="Purpose"
                            width="100"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            label="Status"
                            width="100"
                    >
                    </el-table-column>
                    <el-table-column label="Opr">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    @click="openEdit(scope.row)">Detail
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"/>
                </div>

            </div>

            <div class="modal-wrapper">
                <el-dialog
                        title="Sparepart Request"
                        :visible.sync="dialogVisible"
                        width="80%"
                        top="0px"
                >
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm"
                             :inline="true">
                        <el-form-item label="Request No." prop="requestNo">
                            <el-input class="input" disabled v-model="ruleForm.requestNo"></el-input>
                        </el-form-item>
                        <el-form-item label="Request Date" prop="requestDateStr">
                            <el-date-picker class="input" v-model="ruleForm.requestDateStr"
                                            value-format="yyyy-MM-dd"></el-date-picker>
                        </el-form-item>
                        <el-form-item label="Request By" prop="requestBy">
                            <el-select class="input" v-model="ruleForm.requestBy">
                                <el-option :value="item.id" :key="item.id" :label="item.employeeName"
                                           v-for="item in employeeList"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Customer" prop="customer">
                            <el-select class="input" v-model="ruleForm.customer">
                                <el-option :value="item.customerId" :key="item.customerId" :label="item.customerName"
                                           v-for="item in customerList"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Customer PO" prop="po">
                            <el-input class="input" v-model="ruleForm.customerPo"></el-input>
                        </el-form-item>
                        <el-form-item label="Purpose" prop="purpose">
                            <el-select class="input" v-model="ruleForm.purpose">
                                <el-option :value=1 label="Sale"/>
                                <el-option :value=2 label="Stock"/>
                                <el-option :value=3 label="Warranty"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Approve By" prop="approveBy">
                            <el-select class="input" v-model="ruleForm.approveBy">
                                <el-option :value="item.id" :key="item.id" :label="item.employeeName"
                                           v-for="item in employeeList"/>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <div class="items">
                        <span>items:</span>
                        <label for="file">Upload items</label>
                        <el-input size="small" id="file" style="display: none" type="file">Upload items</el-input>
                        <el-button size="small" type="primary">Check part catalog</el-button>
                        <el-button size="small" type="primary" @click="showDB">Add Items</el-button>
                        <div class="table">
                            <Data-base @deleteItem="deleteItem" :partList="partList"></Data-base>
                        </div>
                    </div>

                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button v-show="ruleForm.status<2 || !ruleForm.status" type="warning" @click="saveRequest">Save</el-button>
                        <el-button v-show="ruleForm.status<2 || !ruleForm.status" type="primary" @click="submitForm">Confirm</el-button>
                    </span>
                </el-dialog>
                <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible"></Part-item>
            </div>
        </div>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import DataBase from '@/components/part/spDataBase'
    import {mapGetters, mapActions} from 'vuex';
    import {ERROR_OK} from "../../util/config";
    import dbMixins from '../../util/spMixins';
    import mixins from '../../util/mixins'
    import {
        getAllPartPurchaseList,
        getRequestNo,
        savePurchaseQuest,
        comfirmPurchaseQuest,
        getPartPurchaseRequestDetail
    } from "../../api/purchase";

    export default {
        name: "purchase-request",
        mixins: [dbMixins, mixins],
        data() {
            return {
                requestList: [],
                partItemList: [],
                ruleForm: {
                    requestNo: '',
                    requestDateStr: '',
                    requestBy: '',
                    customer: '',
                    approveBy: '',
                    customerPo: '',
                    purpose: '',
                    requestDetail: ''
                },
                rules: {
                    requestNo: [
                        {required: true, message: 'Request No is required', trigger: 'blur'},
                    ],
                    requestDateStr: [
                        {required: true, message: 'Request Date is required', trigger: 'change'}
                    ],
                    requestBy: [
                        {required: true, message: 'Request By is required', trigger: 'change'},
                    ],
                    approveBy: [
                        {required: true, message: 'Approved By is required', trigger: 'change'},
                    ],
                    customer: [
                        {required: true, message: 'Name is required', trigger: 'change'}
                    ]
                },
                key: '',
                dialogVisible: false
            }
        },
        computed: {
            purchaseRequestList() {
                return this.requestList.filter(item => item.customer.toLowerCase().indexOf(this.key.toLowerCase()) > -1).slice((this.pageNum - 1) * this.pageSize, this.pageNum * this.pageSize)
            },
            ...mapGetters(['customerList', 'employeeList'])
        },
        beforeRouteEnter(from, to, next) {
            next(vm => {
                vm._getAllList();
                vm.loadCustomerList();
                vm.loadEmployeeList();
            })
        },
        methods: {
            showDB() {
                this.dbVisible = true
            },
            submitForm() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        let list = this.partList.length ? this.partList.map(item => {
                            return {
                                partId: item.id,
                                quantity: item.number
                            }
                        }) : [];
                        list = JSON.stringify(list);
                        this.ruleForm.requestDetail = list;
                        this.$refs.ruleForm.validate(async valid => {
                            if (valid) {
                                let {status} = await comfirmPurchaseQuest(this.ruleForm);
                                if (status === ERROR_OK) {
                                    this.$message({
                                        message: "Confirm Successfully",
                                        type: 'success'
                                    })
                                }
                                this.dialogVisible = false;
                                this._getAllList();
                                this.clear();
                            }
                        })
                    }
                });
            },
            saveRequest() {
                let list = this.partList.length ? this.partList.map(item => {
                    return {
                        partId: item.id,
                        quantity: item.number
                    }
                }) : [];
                list = JSON.stringify(list);
                this.ruleForm.requestDetail = list;
                this.$refs.ruleForm.validate(async valid => {
                    if (valid) {
                        let {status} = await savePurchaseQuest(this.ruleForm);
                        if (status === ERROR_OK) {
                            this.$message({
                                message: "Save Successfully",
                                type: 'success'
                            })
                        }
                        this.dialogVisible = false;
                        this._getAllList();
                        this.clear();
                    }
                })
            },
            clear() {
                // this.$refs.ruleForm.resetFields();
                this.ruleForm = {
                    requestNo: '',
                    requestDateStr: '',
                    requestBy: '',
                    status: 0,
                    customer: '',
                    approveBy: '',
                    customerPo: '',
                    purpose: '',
                    requestDetail: ''
                };
                this.partList = []
            },
            async openAdd() {
                this.clear();
                const {status, data} = await getRequestNo();
                if (status === 0) {
                    this.ruleForm.requestNo = data;
                    this.dialogVisible = true
                } else {
                    this.$message({
                        message: 'Get Request Number error!please retry!',
                        type: 'error'
                    })
                }
            },
            async openEdit(r) {
                this.$nextTick(() => {
                    this.$refs.ruleForm.resetFields()
                });
                let {status, data} = await getPartPurchaseRequestDetail(r.id);
                if (status === ERROR_OK) {
                    this.ruleForm.id = data.id;
                    this.ruleForm.requestNo = data.requestNo;
                    this.ruleForm.requestDateStr = data.requestDate;
                    this.ruleForm.requestBy = data.requestBy;
                    this.ruleForm.approveBy = data.approveBy;
                    this.ruleForm.status = data.status;
                    this.ruleForm.customer = data.customer;
                    this.ruleForm.customerPo = data.customerPo;
                    this.ruleForm.purpose = data.purpose;
                    this.partList = data.spareRequestDetailVoList.map(item => {
                        return {
                            ...item.spareParts,
                            number: item.quantity,
                            stockQuantity: item.stockQuantity
                        }
                    })

                }
                this.dialogVisible = true

            },
            async _getAllList() {
                let {data, status} = await getAllPartPurchaseList();
                if (status === ERROR_OK) {
                    this.requestList = data
                }
            },
            ...mapActions(['loadCustomerList', 'loadEmployeeList'])
        },
        watch: {
            key(key) {
                this.total = this.requestList.filter(item => item.customer.toLowerCase().indexOf(key.toLowerCase()) > -1).length
            }
        },
        components: {
            Crumb,
            Search,
            DataBase,
            PartItem: () => import('@/components/part/sparePartItem')
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .modal-wrapper {
        .input {
            width: 200px;
        }
        .items {
            span {
                display: inline-block;
                width: 140px;
                text-align: right;
                font-size: 16px;
                margin-right: 10px;
            }
            label {
                width: 142px;
                height: 32px;
                display: inline-block;
                text-align: center;
                color: #fff;
                margin-right: 20px;
                cursor: pointer;
                line-height: 32px;
                border-radius: 3px;
                background: #409Eff;
            }
            .table {
                margin-top: 5px;
            }
        }
    }
</style>